package com.ft.controller;

import com.ft.domain.Nongsukeallid;
import com.ft.service.INongsukeallidService;
import com.ft.utils.Code;
import com.ft.utils.Result;
import com.ft.utils.SnowFlakeGenerateIdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/nongsukellid")
@CrossOrigin
public class NongsukeallidController {
    @Autowired
    private INongsukeallidService  service;
    @PostMapping("")
    public Result addOrder(@RequestBody Nongsukeallid order) throws IllegalAccessException {
        //创建订单编号
        SnowFlakeGenerateIdWorker snowFlakeGenerateIdWorker =
                new SnowFlakeGenerateIdWorker(0L,0L);
        String id = snowFlakeGenerateIdWorker.generateNextId();
        order.setId(Long.valueOf(id));
        order.setTitle(order.getTitle()+id);
        int i = service.addOrder(order);
        if(i == 1){
            Nongsukeallid nongsukeallidByOne = service.getNongsukeallidByOne(Long.valueOf(id));
            return new Result(Code.POST_OK, nongsukeallidByOne,"订单创建成功");
        }
        return  new Result(Code.POST_ERR,"订单创建失败");
    }

    @PutMapping("/buystate/{orderid}/{userid}")
    public Result updateOrderState(@PathVariable String orderid,@PathVariable int userid){
        int i = service.updataOrderState(orderid, userid);
        if(i == 1){
            return new Result(Code.PUT_OK,"修改状态成功");
        }
        return new Result(Code.POST_ERR,"修改状态失败");
    }

    @GetMapping("/{userid}")
    public Result getOrderAllToUser(@PathVariable int userid){
        List orderAllToUser = service.getOrderAllToUser(userid);
        return new Result(Code.GET_OK, orderAllToUser,"获取成功");
    }

    /**
     * 购买用户完成订单
     * @param orderid
     * @param userid
     * @return
     */
    @PutMapping("/issueoverorder/{orderid}/{userid}")
    public Result issueOverOrder(@PathVariable String orderid,@PathVariable int userid) throws IOException, IllegalAccessException {
        int i = service.issueOverOrder(orderid, userid);
        if(i == 1){
            return new Result(Code.PUT_OK,"订单已完成");
        }else if(i == 2){
            return new Result(Code.PUT_ERR,"必须付款后才能完成订单喔");
        }
        return new Result(Code.PUT_ERR,"订单完成失败");
    }
}
